package controller;

import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import util.Md5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取用户输入
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        // 检查密码是否一致
        if (!password.equals(confirmPassword)) {
            request.setAttribute("errorMsg", "两次输入的密码不一致");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // 检查用户名是否已存在
        if (userService.isUsernameExists(username)) {
            request.setAttribute("errorMsg", "用户名已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // 使用MD5加密密码
        String encryptedPassword = Md5Util.getMD5String(password);

        // 创建用户对象并注册
        User user = new User(username, encryptedPassword);
        if (userService.register(user)) {
            // 注册成功
            request.setAttribute("registerSuccess", "注册成功");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        } else {
            // 注册失败
            request.setAttribute("errorMsg", "注册失败，请稍后再试");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}